import React,{useState} from 'react'
import '../assets/css/goodslist.scss'
import Dialog from './Dialog'
export default function GoodsList() {
 /*
    调用useState方法
 */
  const [products,setProducts]=useState(()=>{
    return [
        {
            id:'G1001',
            name:'自然堂润肤露',
            price:128,
            salePrice:100,
            status:0
        },
        {
            id:'G1002',
            name:'兰蔻香水',
            price:128,
            salePrice:88,
            status:1
        },
        {
            id:'G1003',
            name:'迪奥口红',
            price:121,
            salePrice:99,
            status:0
        }
    ]
  })
  const [showDialog,setShowDialog]=useState(false)
  const removeGoods=(index)=>{
    products.splice(index,1)
    setProducts([...products])
    //递归的方式进行排序是最权威的写法
    //setProducts(Object.assign([],products))
    //对数组进行深拷贝
    //setProducts([...products])
    //setProducts(JSON.parse(JSON.stringify(products)))
  }
  const switchStatus=(index)=>{
    for(let i=0;i<products.length;i++){
        if(i===index){
            if(products[index].status==0){
                products[index].status=1
            }else if(products[index].status==1){
                products[index].status=0
            }
            break
        }
    }
    console.log('products',products);
    setProducts([...products])
  }
  const getAddProductCallback=(product)=>{
     products.push(product)
     setProducts([...products])
     setShowDialog(false)
  }
  return (
    <div className='box'>
        <button onClick={()=>{setShowDialog(true)}}>添加商品</button>
        <table>
            <thead>
                <tr>
                    <td>商品编号</td>
                    <td>名称</td>
                    <td>价格</td>
                    <td>商城价</td>
                    <td>状态</td>
                    <td>操作</td>
                </tr>
            </thead>
            <tbody>
                {
                   products.map((item,index)=><tr key={item.id}>
                        <td>{item.id}</td>
                        <td>{item.name}</td>
                        <td>{item.price}</td>
                        <td>{item.salePrice}</td>
                        <td>{item.status===1?'上架':item.status===0?'下架':'未知'}</td>
                        <td>
                            <button onClick={()=>{removeGoods(index)}}>删除</button>
                            <button onClick={()=>{switchStatus(index)}}>{item.status===1?'下架':item.status===0?'上架':'未知'}</button>
                        </td>
                   </tr>) 
                }
            </tbody>
        </table>
        {
            showDialog?<Dialog products={products} callback={getAddProductCallback}></Dialog>:<></>
        }
    </div>
  )
}
